package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.service.Impl.LikesServiceImpl;
import com.zja.service.LikesService;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
/**
 * @author JA
 * @date: 2025/5/5
 * description:点赞文章
 */
@WebServlet("/api/article/like")
public class LikeArticleServlet extends HttpServlet {
    private final LikesService likesService = new LikesServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 从 Session 中获取当前用户的 ID
            Long userId = (Long) req.getSession().getAttribute("currentUserId");
            if (userId == null) {
                ServletUtil.writeJsonResponse(resp, JsonResponse.error("请先登录"));
                return;
            }

            Long articleId = Long.parseLong(req.getParameter("articleId"));
            boolean success = likesService.likeArticle(userId, articleId);

            if (success) {
                ServletUtil.writeJsonResponse(resp, JsonResponse.success("点赞成功"));
            } else {
                ServletUtil.writeJsonResponse(resp, JsonResponse.error("已经点赞过该文章"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("点赞失败: " + e.getMessage()));
        }
    }
}
